
#include "bufMap.h"
#include "buf.h"


//Constructor
BufMap::BufMap(const unsigned int numBufs)
{
	maxBufs = numBufs;
}

//---------------------------------------------------------------
// insert entry mapping (file,pageNo) to frameNo;
// returns OK if OK, BUFMAPERROR if an error occurred
//---------------------------------------------------------------

const Status BufMap::insert(File* file, 
				const int pageNo, 
				const unsigned int frameNo)
{
	if(myFrames.size() >= maxBufs)
		return BUFFEREXCEEDED;

	if(frameNo < 0 || frameNo >= maxBufs)
	{
		return BADFRAMEINSERT;
	}
	//check to see if the pointer is already in the frames
	map<pair<File*, int>, unsigned int>::const_iterator it = myFrames.find(make_pair(file, pageNo));

	if(it == myFrames.end())
	{
		myFrames.insert(make_pair(make_pair(file, pageNo), frameNo));
		return OK;
	}
	else
	{
		return BUFMAPERROR;
	}

	
}


//-------------------------------------------------------------------        
// Check if (file,pageNo) is currently in the buffer pool.  If so, 
// return corresponding frameNo. else return BUFMAPNOTFOUND
//-------------------------------------------------------------------

const Status BufMap::lookup(File* file, 
				const int pageNo,
				unsigned int & frameNo) const
{
	map<pair<File*, int>, unsigned int>::const_iterator it = myFrames.find(make_pair(file, pageNo));
	frameNo = it->second;

	if(it != myFrames.end())
	{
		if(frameNo < 0 || frameNo >=  maxBufs)
			return BADFRAMEREAD;

		return OK;
	}
	else
	{
		return BUFMAPNOTFOUND;
	}
}


//-------------------------------------------------------------------
// delete entry (file,pageNo) from mapping. Return OK if page was
// found.  Else if the entry is not found, return BUFMAPNOTFOUND
//-------------------------------------------------------------------

const Status BufMap::remove(File* file, const int pageNo) 
{
	map<pair<File*, int>, unsigned int>::iterator it = myFrames.find(make_pair(file, pageNo));

	if(it == myFrames.end()){
		return BUFMAPNOTFOUND;
	}
	else
	{
		myFrames.erase(it);
		return OK;
	}
}
